import argparse
from contextlib import asynccontextmanager
from typing import AsyncIterator

from aioredis import from_url, Redis
from fastapi import FastAPI

from app_v2.AsyncDataBase import asyncDB
from app_v2.error import init_error_handlers
from app_v2.middleware import init_middleware
from app_v2.routes import init_routes
from app_v2.utils.RedicManager import RedisPool


async def init_redis_pool(host: str, password: str, db: int = 0, port: int = 6379) -> AsyncIterator[Redis]:
    session = await from_url(url=f"redis://{host}", port=port, password=password, db=db, encoding="utf-8",
                             decode_responses=True)
    return session


@asynccontextmanager
async def lifespan(app: FastAPI):
    session = await init_redis_pool(host="127.0.0.1", password="", db=0, port=6379)
    app.state.redis = session
    await asyncDB.connect()
    app.state.db = asyncDB

    async with RedisPool().connect() as pool:
        app.state.redis_pool = pool
        yield

    await asyncDB.disconnect()
    await session.close()


app = FastAPI(lifespan=lifespan)
init_routes(app)
init_middleware(app)
init_error_handlers(app)
